<template>
  <div class="mod_box">
    <el-tabs v-model="tabIndex" type="card" @tab-click="tabgo">
      <el-tab-pane label="一级单位" :disabled="companyLev>1" name="1"></el-tab-pane>
      <el-tab-pane label="二级单位" :disabled="companyLev>2" name="2"></el-tab-pane>
      <el-tab-pane label="三级单位" :disabled="companyLev>3" name="3"></el-tab-pane>
    </el-tabs>
    <el-row>
      <el-col style="text-align: center;">
        <el-input
          v-model.trim="searchMess"
          placeholder="输入单位名称"
          :style="'width:50%;margin:5px 0px;'"
          @keyup.enter.native="search"
        >
          <el-button slot="append" @click="search">搜索</el-button>
        </el-input>
      </el-col>
    </el-row>

    <el-row class="mod_title">
      <el-col :sm="4">
        <div class="g-title">下级单位数目（{{total}}个）</div>
      </el-col>
      <el-col :sm="20" style="text-align: right;">
        <el-button type="primary" v-if="companyLev<tabIndex" @click="add" size="small">新增</el-button>
        <el-button type="warning" @click="editMore" size="small">批量修改</el-button>
        <el-button type="success" @click="edit" size="small">修改</el-button>
        <el-button type="danger" v-if="companyLev==0" @click="del" size="small">删除</el-button>
        <el-button type="primary" v-if="companyLev==0" @click="downloadTpl" size="small">模板下载</el-button>
        <el-button type="primary" v-if="companyLev==0" @click="daoruType = true" size="small">导入</el-button>
        <el-button type="warning" @click="exportData" size="small">导出</el-button>
        <el-button type="warning" @click="AllexportData" size="small">全部导出</el-button>
      </el-col>
    </el-row>

    <el-table
      tooltip-effect="dark"
      border
      :data="listData"
      @selection-change="handleSelectionChange"
      @filter-change="handleFilterChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column fixed prop="index" label="序号" align="center"></el-table-column>
      <el-table-column fixed prop="companyName" label="单位名称" align="center"></el-table-column>
      <el-table-column fixed prop="companyCode" label="单位编码" align="center">
        <template slot-scope="scope">
          <el-button @click="editCode(scope.row)" type="text">{{scope.row.companyCode}}</el-button>
        </template>
      </el-table-column>
      <el-table-column
        fixed
        prop="tagName"
        label="隶属类型"
        align="center"
        :filters="tags"
        column-key="tagId"
      ></el-table-column>
      <el-table-column fixed prop="parentName" label="上级单位" align="center"></el-table-column>
      <el-table-column
        fixed
        prop="propName"
        label="单位性质"
        align="center"
        :filters="propers"
        column-key="xz"
      ></el-table-column>
      <el-table-column
        fixed
        prop="xz"
        label="单位规格"
        align="center"
        :filters="standards"
        column-key="gg"
      ></el-table-column>
    </el-table>

    <el-row style="padding: 32px 16px;">
      <el-col>
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-size="pageSize"
          :total="total"
          :current-page="pageNo"
          @current-change="fetchData"
          @size-change="pageSizeChange"
        ></el-pagination>
      </el-col>
    </el-row>

    <el-dialog
      title="修改单位编码"
      ref="tableDialog"
      :visible.sync="changeCodeType"
      border
      width="80%"
      v-if="changeCodeType"
    >
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="form">
        <el-row>
          <el-col :sm="24">
            <el-form-item label="单位编码" prop="code">
              <el-input v-model="formData.code" placeholder="请输入单位编码">
                <template slot="prepend">{{formData.codeTitle}}</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer" style="text-align: left;">
        <el-button type="primary" @click="saveCode">保存数据</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="批量隶属类型修改"
      ref="tableDialog"
      border
      :visible.sync="EditMoreType"
      v-if="EditMoreType"
      width="80%"
    >
      <h3>单位信息</h3>
      <el-table :data="listDataSelected" border style="width: 100%">
        <el-table-column type="index" label="序号" width="180" align="center"></el-table-column>
        <el-table-column prop="companyCode" label="单位编码" align="center"></el-table-column>
        <el-table-column prop="companyName" label="名称"></el-table-column>
        <el-table-column prop="tagName" label="隶属类型" width="200" align="center"></el-table-column>
        <el-table-column prop="propName" label="单位规格" align="center"></el-table-column>
        <el-table-column prop="xz" label="单位性质" align="center" width="120"></el-table-column>
      </el-table>
      <h3>修改类型</h3>
      <el-form :model="formData" label-width="120px" :rules="formRules" ref="form">
        <el-row>
          <el-col :sm="8">
            <el-form-item label="隶属类型" prop="tagId" v-if="tabIndex=='1'">
              <el-select v-model="formData.tagId" placeholder="批量选择隶属类型" style="width: 100%;">
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="(item, index) in tags"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="8">
            <el-form-item label="单位规格" prop="gg">
              <el-select v-model="formData.gg" placeholder="批量选择单位规格" style="width: 100%;">
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="(item, index) in standards"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="8">
            <el-form-item label="单位性质" prop="xz">
              <el-select v-model="formData.xz" placeholder="批量选择单位性质" style="width: 100%;">
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="(item, index) in propers"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateTag">确 定</el-button>
      </span>
    </el-dialog>
    <changeDw
      v-if="dialogVisible"
      :dialog-visible.sync="dialogVisible"
      :companyId="companyId"
      :level="tabIndex"
      @finish="fetchData"
    ></changeDw>
    <el-dialog title="导入单位信息" :visible.sync="daoruType" width="70%">
      <el-upload
        ref="upload"
        class="upload_exl"
        drag
        :action="serverProjName+'common/webupload.shtml'"
        multiple
        :on-success="uploadSuccess"
        :on-exceed="onExceed"
        :limit="1"
        :on-remove="onRemove"
        :before-upload="beforeUpload"
      >
        <el-button type="primary" size="mini">请选择要上传的EXCEL</el-button>
      </el-upload>
      <br />
      <div style="text-align:center">
        <el-button type="primary" @click="daoru()">确认导入</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss">
.mod_box {
  padding: 20px;
}
.mod_title {
  padding: 20px 0;
  .g-title {
    height: 20px;
    padding-left: 8px;
    line-height: 22px;
    font-size: 16px;
    font-weight: 400;
    border-left: 2px solid #f54e40;
    margin: 10px 0;
    display: inline-block;
  }
  .eluploadwrapper {
    display: inline-block;
    margin: 0 10px;
  }
}

.eluploadwrapper {
  display: inline-block;
  margin-left: 10px;
}
.upload_exl .el-upload,
.upload_exl .el-upload-dragger {
  width: 100%;
}

.upload_exl .el-upload-dragger .el-button {
  margin-top: 76px;
}
</style>
<script>
import { axios } from "@/api/axios";
import { mapGetters } from "vuex";
import changeDw from "./components/changeDw/index";
export default {
  components: { changeDw },
  data: function() {
    return {
      companyLev: null,
      tabIndex: "2",
      searchMess: "",
      total: 0,
      pageNo: 1,
      pageSize: 10,
      listData: [],
      listDataSelected: [], //选中数据
      dialogVisible: false,
      changeCodeType: false,
      EditMoreType: false,
      propers: [],
      standards: [],
      tags: [],
      tagId: "",
      xz: "",
      gg: "",
      companyId: null,
      formData: null,
      fileurl: "",
      daoruType: false,
      formRules: {
        code: [
          {
            validator: (rule, value, callback) => {
              let intVal = Number.parseInt(value) || 0;
              if (intVal > 999) {
                this.formData.code = "999";
              } else if (intVal <= 0) {
                this.formData.code = "001";
              } else if ((intVal + "").length == 1) {
                this.formData.code = "00" + intVal;
              } else if ((intVal + "").length == 2) {
                this.formData.code = "0" + intVal;
              } else {
                this.formData.code = intVal + "";
              }
              callback();
            },
            trigger: "blur"
          }
        ]
      },
      uploadFileParams: {
        a: 1
      }
    };
  },
  methods: {
    tabgo() {
      this.pageNo = 1;
      this.fetchData();
    },
    add() {
      this.companyId = null;
      this.dialogVisible = true;
    },
    edit() {
      if (this.listDataSelected.length == 0) {
        this.$message("请选择");
        return;
      }
      this.companyId = this.listDataSelected[0].id;
      this.dialogVisible = true;
    },
    editMore() {
      if (this.listDataSelected.length == 0) {
        this.$message("请选择");
        return;
      }
      var formOld = JSON.parse(JSON.stringify(this.listDataSelected));
      var formNow = "";
      for (var key in formOld) {
        formNow = formNow + "," + formOld[key].id;
      }
      var formNow = formNow.slice(1);
      this.formData = {
        companyId: formNow,
        tagId: "",
        xz: "",
        gg: ""
      };
      axios("/admin/company/showDetails2.do", "get", {
        level: this.tabIndex
      }).then(data => {
        this.propers = data.propers;
        this.standards = data.standards;
        this.tags = data.tags;
      });
      this.EditMoreType = true;
    },
    updateTag() {
      this.$refs.form.validate(pass => {
        if (!pass) {
          return;
        }
        this.$confirm("是否确认修改?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            var formData = JSON.parse(JSON.stringify(this.formData));
            var param = new URLSearchParams();
            for (var key in formData) {
              if (formData[key] instanceof Array) {
                param.append(key, formData[key].join(","));
              } else {
                param.append(
                  key,
                  typeof formData[key] === "undefined" ? "" : formData[key]
                );
              }
            }
            axios("/admin/company/updateTag.do", "post", param).then(data => {
              if (data.error == 0) {
                this.$message.success("保存成功");
                this.EditMoreType = false;
                this.fetchData();
              } else {
                this.$message.error("保存失败");
              }
            });
          })
          .catch(() => {});
      });
    },
    del() {
      if (this.listDataSelected.length == 0) {
        this.$message("请选择");
        return;
      }
      this.$confirm("是否确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let url = "/admin/company/removeCompany.do";
          let ids = this.listDataSelected
            .map(function(e) {
              return e.id;
            })
            .join(",");

          axios(url, "post", { ids: ids }).then(
            data => {
              console.log(data);
              if (data.error == 0) {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                this.fetchData();
              } else {
                this.$message({
                  type: "warning",
                  message: data.errorMsg
                });
              }
            }
          );
        })
        .catch(() => {});
    },
    editCode(val) {
      this.formData = {
        companyId: val.id,
        code: val.companyCode.substring(val.companyCode.length - 3),
        codeTitle: val.companyCode.substring(0, val.companyCode.length - 3)
      };
      this.changeCodeType = true;
    },
    saveCode() {
      this.$refs.form.validate(pass => {
        if (!pass) {
          return;
        }
        this.$confirm("是否确认修改?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            var formData = JSON.parse(JSON.stringify(this.formData));
            var param = new URLSearchParams();
            for (var key in formData) {
              if (formData[key] instanceof Array) {
                param.append(key, formData[key].join(","));
              } else {
                param.append(
                  key,
                  typeof formData[key] === "undefined" ? "" : formData[key]
                );
              }
            }
            axios("/admin/company/updateCode2.do", "post", param).then(data => {
              if (data.error == 0) {
                this.$message.success("保存成功");
                this.changeCodeType = false;
                this.fetchData();
                //刷新左侧单位树
                this.$store.dispatch("user/getLeftJson");
              } else {
                this.$message.error("保存失败");
              }
            });
          })
          .catch(() => {});
      });
    },
    //下载模板
    downloadTpl(files) {
      var form = document.createElement("form");
      form.setAttribute(
        "action",
        this.serverProjName + "upload/temp/单位导入模板.xlsx"
      );
      form.setAttribute("method", "get");
      document.body.append(form);
      form.submit();
    },
    beforeUpload(file) {
      var FileExt = file.name.replace(/.+\./, "");
      if (["xlsx"].indexOf(FileExt.toLowerCase()) === -1) {
        this.$message({
          type: "warning",
          message: "请上传后缀名为xlsx的文件！"
        });
        return false;
      }
    },
    uploadSuccess(file) {
      if (!file) return;
      console.log(file);
      if (file.error == 0) {
        console.log(this.VUE_APP_BASE_API + file.url);
        this.fileurl = file.url;
      } else {
        this.$message("上传失败，请重试");
      }
    },

    onRemove() {
      this.fileurl = "";
    },
    onExceed() {
      this.$message("只能上传1个文件，请先移除已上传文件再上传");
    },
    daoru() {
      if (this.fileurl == "") {
        this.$message("请上传文件");
        return;
      }
      let url = "/admin/company/import.do";
      let params = { dir: this.fileurl };
      axios(url, "post", params).then(data => {
        if (data.error == 0) {
          if (data.errorMsg) {
            data.errorMsg = data.errorMsg.replace(/^,+/, "").replace(/,+$/, "");
            this.$message({ message: data.errorMsg });
          } else {
            this.$message("导入成功");
          }
          this.fileurl = "";
          this.$refs.upload.clearFiles();
          this.fetchData();
          this.daoruType = false;
        } else {
          this.$message("导入失败，请重试");
        }
      });
    },
    //导出
    exportData() {
      if (this.listDataSelected.length == 0) {
        this.$message("请选择");
        return;
      }
      var headers =
        "序号,单位编码,单位名称,隶属类型,隶属类别,上级单位,单位性质,单位规格";
      var data = this.listDataSelected.map(function(e) {
        return {
          index: e.index || "",
          companyCode: e.companyCode || "",
          companyName: e.companyName || "",
          tagName: e.tagName || "",
          subLevName: "省直部门及所属单位",
          parentName: e.parentName || "",
          propName: e.propName || "",
          xz: e.xz || ""
        };
      });
      this.jsonToExcel(data, headers);
    },
    //导出
    AllexportData() {
      this.$confirm("是否全部导出?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let loading = this.$loading({ text: "数据较多，请耐心等待" });
        axios("/admin/company/levelListJson.do", "get", {
          level: this.tabIndex,
          pageNo: this.pageNo,
          pageSize: this.total,
          companyName: this.searchMess,
          tagId: this.tagId,
          xz: this.xz,
          gg: this.gg,
          comIds: this.selectedComIds.join(",")
        })
          .then(data => {
            loading.close();
            var alldata = data.data;
            var headers =
              "序号,单位编码,单位名称,隶属类型,隶属类别,上级单位,单位性质,单位规格";
            var Outdata = alldata.map(function(e,index) {
              return {
                index: index+1,
                companyCode: e.companyCode || "",
                companyName: e.companyName || "",
                tagName: e.tagName || "",
                subLevName: "省直部门及所属单位",
                parentName: e.parentName || "",
                propName: e.propName || "",
                xz: e.xz || ""
              };
            });
            this.jsonToExcel(Outdata, headers);
          })
          .catch(e => {
            loading.close();
            this.$message({
              message: "导出失败，请重试",
              type: "error"
            });
          });
      });
    },
    //json导出excel
    jsonToExcel(jsonData, headers) {
      //列标题，逗号隔开，每一个逗号就是隔开一个单元格
      var str = headers + "\n";
      //增加\t为了不让表格显示科学计数法或者其他格式
      for (var i = 0; i < jsonData.length; i++) {
        for (var item in jsonData[i]) {
          str += jsonData[i][item] + "\t,";
        }
        str += "\n";
      }
      //encodeURIComponent解决中文乱码
      var uri = "data:text/csv;charset=utf-8,\ufeff" + encodeURIComponent(str);
      //通过创建a标签实现
      var link = document.createElement("a");
      link.href = uri;
      //对下载的文件命名
      link.download = "导出数据表.csv";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    fetchData(pageNo) {
      if (pageNo) {
        this.pageNo = pageNo;
      }
      axios("/admin/company/levelListJson.do", "get", {
        level: this.tabIndex,
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        companyName: this.searchMess,
        tagId: this.tagId,
        xz: this.xz,
        gg: this.gg,
        comIds: this.selectedComIds.join(",")
      }).then(data => {
        this.listData = data.data;
        for (var i in this.listData) {
          this.listData[i].index =
            Number(i) + Number(this.pageSize * (this.pageNo - 1)) + 1;
        }
        this.total = data.total;
      });
    },
    getlist() {
      axios("/admin/company/showDetails2.do", "get", {
        level: this.tabIndex
      }).then(data => {
        data.tags.map(value => {
          this.tags.push({ value: value.id, text: value.name });
        });
        data.propers.map(value => {
          this.propers.push({ value: value.id, text: value.name });
        });
        data.standards.map(value => {
          this.standards.push({ value: value.id, text: value.name });
        });
      });
    },
    search() {
      this.pageNo = 1;
      this.fetchData();
    },
    pageSizeChange(newSize) {
      this.pageSize = newSize;
      this.pageNo = 1;
      this.fetchData();
    },
    //表头搜索
    handleFilterChange(filters) {
      if (filters["tagId"]) {
        this.tagId = filters["tagId"].join(",");
      }
      if (filters["xz"]) {
        this.xz = filters["xz"].join(",");
      }
      if (filters["gg"]) {
        this.gg = filters["gg"].join(",");
      }
      this.fetchData();
    },
    //表格多选
    handleSelectionChange(val) {
      this.listDataSelected.splice(0);
      val.forEach(e => {
        this.listDataSelected.push(e);
      });
      console.log(this.listDataSelected);
    }
  },
  computed: {
    ...mapGetters(["userInfo", "selectedComIds"])
  },
  watch: {
    //监听左侧单位勾选 重新获取数据
    selectedComIds() {
      this.pageNo = 1;
      this.fetchData();
    }
  },
  created() {
    this.serverProjName = this.VUE_APP_BASE_API;
    this.companyLev = this.userInfo.companyLev;
    if (this.companyLev == 0) {
      this.tabIndex = "1";
    } else {
      this.tabIndex = this.companyLev.toString();
    }
    this.getlist();
    this.fetchData();
    console.log(this.tags);
  }
};
</script>